package com.groot.medical.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.google.gson.Gson;
import com.groot.common.controller.BaseServletController;
import com.groot.common.util.ExcelUtil;
import com.groot.common.util.SimpleDateUtil;
import com.groot.medical.entity.AdministrativeArea;
import com.groot.medical.entity.ChronicDisease;
import com.groot.medical.entity.ChronicExpense;
import com.groot.medical.entity.Menu;
import com.groot.medical.entity.PageBean;
import com.groot.medical.entity.SysUser;
import com.groot.medical.service.AdministrativeAreaService;
import com.groot.medical.service.AdministrativeAreaServiceImpl;
import com.groot.medical.service.ChronicExamineService;
import com.groot.medical.service.ChronicExamineServiceImpl;
import com.groot.medical.service.ChronicExpenseService;
import com.groot.medical.service.ChronicExpenseServiceImpl;
import com.groot.medical.service.ChronicPatternService;
import com.groot.medical.service.ChronicPatternServiceImpl;
import com.groot.medical.service.ChronicPolicyService;
import com.groot.medical.service.ChronicPolicyServiceImpl;
import com.groot.medical.service.ChronicService;
import com.groot.medical.service.ChronicServiceImpl;
import com.groot.medical.service.PayService;
import com.groot.medical.service.PayServiceImpl;
import com.groot.medical.service.PersonalFileService;
import com.groot.medical.service.PersonalFileServiceImpl;
@WebServlet("/sys/examine.do")
public class ChronicExamineController extends BaseServletController{
	private static final long serialVersionUID = 1L;
	private ChronicPatternService chronicPatternService = new ChronicPatternServiceImpl();
	private ChronicService chroniceService = new ChronicServiceImpl();
	private ChronicExpenseService chronicExpenseService = new ChronicExpenseServiceImpl();
	private PersonalFileService personalFileService = new PersonalFileServiceImpl();
	private PayService payService = new PayServiceImpl();
	private ChronicPolicyService chronicPolicyService = new ChronicPolicyServiceImpl();
	private ChronicExamineService chronicExamineService = new ChronicExamineServiceImpl();
	private static Logger LOGGER = Logger.getLogger(ChronicExamineController.class);
	private AdministrativeAreaService areaService = new AdministrativeAreaServiceImpl();
	
	public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOGGER.info("this is @WebServlet(\"/index.do\").execute()");
		return null;
	}
	/**
	 * 审核汇款列表
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	public String findChronicExamineByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//session获取用户信息
		SysUser sysUser = (SysUser) request.getSession().getAttribute("sysUser");
		//接受页面参数
		String ispass = request.getParameter("ispass");
		String isremittance = request.getParameter("isremittance");
		String areacode = request.getParameter("areacode");
		String name = request.getParameter("name");
		String stratTime = request.getParameter("stratTime");
		String endTime = request.getParameter("endTime");
		String tgId = request.getParameter("tgId");
		int pageNum = Integer.valueOf(request.getParameter("pageNum"));
		List<Menu> menus=(List<Menu>) request.getSession().getAttribute("menuList");
		List<Menu> result = new ArrayList<Menu>();
		/*根据页面传过来的id与该用户所有权限的上一级id比较
		 * 若该权限的上一级传过来的id相同则存入新集合
		 */
		for(Menu menu: menus){
			if(menu.getMenuPid().equals(tgId)){
				result.add(menu);
			}
		}
		//根据用户等级判断行政区域
		if(areacode==null){
			areacode=sysUser.getAreaCode();
		}
		//根据用户所在区域显示对应数据
		if(sysUser.getAreaCode().length()==6){
			ispass="1";
		}
		request.setAttribute("resultMenus", result);
		System.out.println("权限："+result);
		request.setAttribute("tgId", tgId);
		//---------------------------------------
		ispass=ispass==null || "".equals(ispass)? "" : ispass;
		isremittance=isremittance==null || "".equals(isremittance)? "" : isremittance;
		areacode=areacode==null || "".equals(areacode)? "" : areacode;
		name=name==null || "".equals(name)? "" : name;
		stratTime=stratTime==null || "".equals(stratTime)? "" : stratTime;
		endTime=endTime==null || "".equals(endTime)? "" : endTime;
		String year="&ispass="+ispass+"&isremittance="+isremittance+"&areacode="+areacode+"&name="+name+"&stratTime="+stratTime+"&endTime="+endTime;
		//------------------------
		int pageSize = 5;
		List<AdministrativeArea> towns = areaService.findAllTownInfo();	
		System.out.println("区域编号是多少"+areacode);
	    PageBean areaPage = chronicExamineService.findChronicExamineByPage(pageNum, pageSize,name,stratTime,endTime,areacode,ispass,isremittance);
		System.out.println(areaPage);
		request.setAttribute("areaPage", areaPage);
		request.setAttribute("towns", towns);
		request.setAttribute("year", year);
		System.out.println(sysUser);
		return "/WEB-INF/page/expense/expense_list.jsp";
	}
	/**
	 * 审核
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void passExpense(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		System.out.println(id);
		String resultString = "false";
		int flag=chronicExpenseService.passExpense(id);
		System.out.println(flag);
		if(flag>0){
			resultString = "true";
			response.setContentType("text/html");
	        ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(resultString.getBytes());
	        outputStream.close();
		}else{
			resultString = "false";
			response.setContentType("text/html");
	        ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(resultString.getBytes());
	        outputStream.close();
		}
	}
	/**
	 * 汇款
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void RemittanceExpense(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		System.out.println(id);
		String resultString = "false";
		int flag=chronicExpenseService.RemittanceExpense(id);
		System.out.println(flag);
		if(flag>0){
			resultString = "true";
			response.setContentType("text/html");
	        ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(resultString.getBytes());
	        outputStream.close();
		}else{
			resultString = "false";
			response.setContentType("text/html");
	        ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(resultString.getBytes());
	        outputStream.close();
		}
	}
	/**
	 * 慢性病报销统计
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	public String statisticsChronicExpense(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//session获取用户信息
				SysUser sysUser = (SysUser) request.getSession().getAttribute("sysUser");
				//接受页面参数
				
				String areacode = request.getParameter("areacode");
				String name = request.getParameter("name");
				String stratTime = request.getParameter("stratTime");
				String endTime = request.getParameter("endTime");
				String illCode = request.getParameter("illCode");
				String tgId = request.getParameter("tgId");
				int pageNum = Integer.valueOf(request.getParameter("pageNum"));
				List<Menu> menus=(List<Menu>) request.getSession().getAttribute("menuList");
				List<Menu> result = new ArrayList<Menu>();
				/*根据页面传过来的id与该用户所有权限的上一级id比较
				 * 若该权限的上一级传过来的id相同则存入新集合
				 */
				for(Menu menu: menus){
					if(menu.getMenuPid().equals(tgId)){
						result.add(menu);
					}
				}
				//根据用户等级判断行政区域
				if(areacode==null){
					areacode=sysUser.getAreaCode();
				}
				request.setAttribute("resultMenus", result);
				System.out.println("权限："+result);
				request.setAttribute("tgId", tgId);
				//---
				illCode=illCode==null || "".equals(illCode)? "" : illCode;
				areacode=areacode==null || "".equals(areacode)? "" : areacode;
				name=name==null || "".equals(name)? "" : name;
				stratTime=stratTime==null || "".equals(stratTime)? "" : stratTime;
				endTime=endTime==null || "".equals(endTime)? "" : endTime;
				
				String year="&illCode="+illCode+"&areacode="+areacode+"&areacode="+areacode+"&name="+name+"&stratTime="+stratTime+"&endTime="+endTime;
				//---
				int pageSize = 5;
				
				
				System.out.println("统计："+areacode);
				//查询所有镇的信息
				List<AdministrativeArea> towns = areaService.findAllTownInfo();	
				//查询所有慢性病信息
				List<ChronicDisease> chronicInfos=chroniceService.findAllChronicInfo();
				//模糊分页统计慢性病统计信息
			    PageBean areaPage = chronicExamineService.statisticsChronicExpense(pageNum, pageSize,name,stratTime,endTime,areacode,illCode);
				System.out.println(areaPage);
				request.setAttribute("areaPage", areaPage);
				request.setAttribute("towns", towns);
				request.setAttribute("chronicInfos", chronicInfos);
				request.setAttribute("year", year);
				System.out.println(sysUser);
				return "/WEB-INF/page/expense/expense_tongji.jsp";
	}
	
	public String outExcelResoult(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//illCode=&areacode=&areacode=&name=&stratTime=&endTime=
		String illCode =request.getParameter("illCode");
		String areacode =request.getParameter("areacode");
		String name =request.getParameter("name");
		String stratTime =request.getParameter("stratTime");
		String endTime =request.getParameter("endTime");
		
		//根据条件查询信息
		List<ChronicExpense> expense = chronicExamineService.findByCondition(name,stratTime,endTime,areacode,illCode);
		System.out.println("_+_+_+_+_"+expense);
		//
		String[][] content=null;
		String[] title = {"序号","身份证号","农合证号","报销金额","姓名","报销病种","当前年份","审核状态","汇款状态"};
		//
		 String fileName = "统计信息"+SimpleDateUtil.now()+".xls";
		 String sheetName = "慢性病报销统计表";
		 		content= new String[expense.size() ][ title.length ];
		 		
				    
				for (int i = 0; i < expense.size(); i++) {
			 
		 		ChronicExpense obj = expense.get(i);
	            content[i][0] = String.valueOf(obj.getId());
	            content[i][1] = obj.getIdCardNumber();
	            content[i][2] = obj.getFarmingCardCode();
	            content[i][3] = String.valueOf(obj.getExpenseMoney());
	            content[i][4] = obj.getHospitalTicket();
	            content[i][5] = obj.getIllCode();
	            content[i][6] = obj.getCurrentYear();
	            content[i][7] = String.valueOf(obj.getIsPass()==0?"未审核":"已审核");
	            content[i][8] = String.valueOf(obj.getIsRemittance()==0?"未汇款":"已汇款");
	            
	            }
		 		//创建HSSFWorkbook 
		 		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
		 		//响应到客户端
		 		try {
		 			this.setResponseHeader(response, fileName);
		 			OutputStream os = response.getOutputStream();
		 			wb.write(os);
		 			os.flush();
		 			os.close();
		 			} catch (Exception e) {
		 				e.printStackTrace();
		 				}
		return null;
	}
	//发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
